package com.smalldragon.yml.config;

import com.smalldragon.yml.interceptors.AuthInterceptor;
import com.smalldragon.yml.interceptors.constants.InterceptorOrder;
import com.smalldragon.yml.propertity.DragonTokenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private AuthInterceptor authInterceptor;
    
    @Resource
    private DragonTokenProperties dragonTokenProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 🚀 登录认证及鉴权拦截器 - 最高优先级执行
        // 必须在所有业务逻辑之前执行，确保用户上下文和租户信息已设置
        registry.addInterceptor(authInterceptor)
                .order(InterceptorOrder.AUTHENTICATION)  // -1000，确保最优先执行
                .addPathPatterns("/**")
                .excludePathPatterns(getExcludePaths());

    }

    /**
     * 获取所有需要排除的路径
     * 包括：配置文件白名单 + 系统默认排除路径
     */
    private String[] getExcludePaths() {
        List<String> excludePaths = new ArrayList<>();

        // 1. 添加配置文件中的白名单路径（防止空指针）
        String[] configWhitePaths = dragonTokenProperties.getWhitePaths();
        if (configWhitePaths != null) {
            for (String path : configWhitePaths) {
                if (path != null && !path.trim().isEmpty()) {
                    excludePaths.add(path.trim());
                }
            }
        }

        // 2. 添加系统默认排除路径
        String[] systemDefaultPaths = {
            "/error",                    // Spring Boot 错误页面
            "/actuator/**",             // 监控端点
            "/swagger-ui/**",           // Swagger UI
            "/v3/api-docs/**",          // OpenAPI 文档
            "/webjars/**",              // WebJars 资源
            "/favicon.ico",             // 网站图标
            "/static/**",               // 静态资源
            "/public/**"                // 公开资源
        };
        excludePaths.addAll(Arrays.asList(systemDefaultPaths));

        return excludePaths.toArray(new String[0]);
    }



}
